import JQuery from 'jquery';
import config from '@/js/util/config.js';
import { Message } from 'element-ui';
import queue from '@/js/util/queue.js';
import user from '@/js/util/user.js';

let runningQueue = new queue.TaskQueue();
let stopQueue = new queue.TaskQueue();
let panal = null;
function paramFun() {
    var param = [{
        token: user.getUploadToken()
    },
    {
        token: user.getUploadToken()
    }
    ];
    return param;
};

runningQueue.executeFun = function(task) {
    task.upload();
};

runningQueue.stopFun = function(task, running) {
    task._isrunning = running;
};

runningQueue.changeTaskFun = function(queue) {
    // store.commit('setUploadNum', runningQueue.getQueue().length + stopQueue.getQueue().length)
};

stopQueue.changeTaskFun = function(queue) {
    // store.commit('setUploadNum', runningQueue.getQueue().length + stopQueue.getQueue().length)
};

let upload = {
    runningQueue: runningQueue,
    stopQueue: stopQueue,
    setCreateUploadPanel: function(arg) {
        panal = arg;
    },
    createUploadPanel: function() {
        if (panal) {
            panal();
        };
    },
    addFile: function(file, type, attribute, createImageFun, createErrorFun) {
        let _this = this;
        if (file) {
            const fileUp = new queue.MultiPartUpload();
            fileUp.url = [
                `${config.getServiceURL('scene')}service/scene/upload/process`,
                `${config.getServiceURL('scene')}service/scene/resource/upload`
            ];
            fileUp.param = [{},
            {
                type: type,
                attribute: attribute
            },
            ];
            fileUp.filetype = type;
            fileUp.autoSpeed = true;
            fileUp.limit = 1048576;
            fileUp.minLimit = 1024;
            fileUp.waitTime = 10000;
            fileUp.maxFile = 1099511627776; // 生产环境每个文件最大1TB
            //fileUp.maxFile = 536870912;// 测试环境每个文件最大512MB
            fileUp.paramFun = paramFun;
            fileUp.beforeFun = function(up) {
                up.formData.set('token', user.getUploadToken());
            };
            fileUp.getUploadFlag = function(response) {
                let mess = '0';
                try {
                    mess = response.body.message.state;
                } catch (e) { }
                return mess;
            };
            if (createImageFun) {
                fileUp.createImageFun = createImageFun;
            }
            if (createErrorFun) {
                fileUp.createErrorFun = createErrorFun;
            }
            fileUp.errorFun = function(up) {
                if (up.createErrorFun) {
                    up.createErrorFun(up);
                }
                runningQueue.removeTask(up);
                _this.createUploadPanel();
            }
            fileUp.finishFun = function(up) {
                if (up.isFinish()) {
                    runningQueue.removeTask(up);
                    if (up.createImageFun) {
                        up.createImageFun(up);
                    }
                    _this.createUploadPanel();
                } else if (up._isdelete) {
                    deleteUploadFile(up);
                    delete up._isdelete;
                } else {
                    runningQueue.removeTask(up);
                    stopQueue.addTask(up);
                    _this.createUploadPanel();
                }
            };
            if (fileUp.setFile(file)) {
                let list0 = runningQueue.getQueue();
                let list1 = stopQueue.getQueue();
                let add = true;
                for (let i = 0; i < list0.length; i++) {
                    if (
                        list0[i].name == fileUp.name &&
                        list0[i].fileSize == fileUp.fileSize
                    ) {
                        add = false;
                        break;
                    }
                }
                for (let i = 0; i < list1.length; i++) {
                    if (
                        list1[i].name == fileUp.name &&
                        list1[i].fileSize == fileUp.fileSize
                    ) {
                        add = false;
                        break;
                    }
                }
                if (add) {
                    Message({
                        type: 'success',
                        message: '文件正在上传中！'
                    });
                    runningQueue.addTask(fileUp);
                    _this.createUploadPanel();
                    runningQueue.execute(0);
                }
            } else {
                let bean = formatDocSize(fileUp.maxFile);
                Message({
                    type: 'error',
                    message: '上传文件超出' + bean.size.toFixed(2) + bean.unit
                });
            }
        } else {
            Message({
                type: 'error',
                message: '没有选择文件'
            });
        }
    },
    start: function(index) {
        let task = stopQueue.removeTaskAt(index);
        if (task) {
            runningQueue.addTask(task);
            this.createUploadPanel();
            runningQueue.execute(0);
        } else {
            Message({
                type: 'error',
                message: '没有可开始上传的文件'
            });
        }
    },
    stop: function(index) {
        let task = runningQueue.removeTaskAt(index);
        if (task) {
            if (task._isrunning) {
                task.stop();
            }
            delete task._isrunning;
            stopQueue.addTask(task);
            this.createUploadPanel();
        } else {
            Message({
                type: 'error',
                message: '没有可停止上传的文件'
            });
        }
    },
    deleteRunFile: function(index) {
        let task = runningQueue.removeTaskAt(index);
        if (task) {
            // 删除没有正在运行的，不走finish方法
            if (!task._isrunning) {
                deleteUploadFile(task);
            } else {
                // 给任务标识删除
                task._isdelete = true;
                // 停止任务
                task.stop();
            }
            this.createUploadPanel();
            delete task._isrunning;
        } else {
            Message({
                type: 'error',
                message: '没有可删除的文件'
            });
        }
    },
    deleteStopFile: function(index) {
        let task = stopQueue.removeTaskAt(index);
        if (task) {
            this.createUploadPanel();
            this.deleteUploadFile(task);
        } else {
            Message({
                type: 'error',
                message: '没有可删除的文件'
            });
        }
    },
    deleteUploadFile: function(up) {
        JQuery.ajax({
            url: `${config.getServiceURL('scene')}service/server/delete`,
            type: 'POST',
            data: {
                filename: up.name,
                size: up.fileSize,
                // 这要get新token
                token: user.getUploadToken()
            },
            dataType: 'json',
            success: function(responseText) { },
            error: function(responseText) { }
        });
    }
};

export default upload;
